from odoo import api, fields, models, _
from odoo.exceptions import UserError


class Feedback(models.Model):
    _name = 'user.feedback'
    _description = '药品群体不良事件基本信息表'

    name = fields.Char(
        '反馈表详情',
        default='反馈表详情'
    )
    vaccine_organization = fields.Many2one(
        'vaccine.organization',
        string='接种点',
        required=True
    )
    feedback_no = fields.Char(
        '反馈编号',
        index=True,
        readonly=True,
        default='自动生成'
    )

    @api.model
    def create(self, vals):
        """
        自动生成单号
        :return:
        """
        vals['feedback_no'] = self.env['ir.sequence'].next_by_code('user.feedback') or ''
        return super(Feedback, self).create(vals)

    department = fields.Selection([
        ('内科', '内科'),
        ('外科', '外科'),
        ('儿科', '儿科'),
        ('妇科', '妇科'),
        ('耳鼻喉科', '耳鼻喉科'),
    ], string='科室', defaut='内科', index=True)
    description = fields.Html(
        '过程描述',
        required=True
    )
    show = fields.Char(
        '表现'
    )
    result = fields.Selection([
        ('痊愈', '痊愈'),
        ('好转', '好转'),
        ('未好转', '未好转'),
        ('不详', '不详'),
        ('有后遗症', '有后遗症'),
        ('死亡', '死亡'),
    ], string='结果', defaut='痊愈', index=True)
    stop_recover = fields.Boolean(
        '停止注射后，反应/事件是否有减弱',
        default=True
    )

    def submit_feedback(self):
        self.ensure_one()
        # 检验此数据集中是否包含单条数据，否则报错
        sql_query = """SELECT name FROM feedback_search where feedback_no = '{feedback_no}'""".format(
            feedback_no=self.feedback_no)
        self.env.cr.execute(sql_query)
        result = self.env.cr.dictfetchall()
        # 通过原生sql检验当前疫苗的id是否在问题疫苗表中有对应的数据
        if result:
            raise UserError(_('编号%s的反馈已被提交过!') % self.feedback_no)
        # 有则报错
        else:
            return {
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form,tree',
                'res_model': 'feedback.search',
                'target': 'new',
                'context': {
                    'default_feedback_no': self.feedback_no,
                    'default_department': self.department,
                    'default_description': self.description,
                    'default_show': self.show,
                    'default_result': self.result,
                    'default_stop_recover': self.stop_recover,
                    'default_vaccine_organization': self.vaccine_organization.id,
                }
            }
            # 此处return作为悬浮式页面跳转
